<?php

namespace app\api\controller\v1;

use app\common\lib\Str;
use app\common\lib\Toutiao;
use app\common\model\MallAccessToken;
use app\common\model\MallBonus;
use app\common\model\MallCollect;
use app\common\model\MallDoorGoods;
use app\common\model\MallGoods;
use app\common\lib\Show;
use app\common\lib\Status;
use app\common\model\MallBanner;
use app\common\model\MallGoodsSku;
use app\common\model\MallHistory;
use app\common\model\MallManagerDoor;
use app\common\model\MallSpecs;
use app\common\model\MallSpecsValue;
use app\common\model\MallTags;
use app\common\model\MallUserBonus;
use think\facade\Log;

class Index extends Base
{
    public function index(){
        $page =$this->request->param('page',1,'intval');
        $limit =$this->request->param('limit',10,'intval');
        try{
            $banner =(new MallBanner())->getBaseByWhere([['status','=',1],['type','=',1]],'id,logo,linkurl');
            $goods =(new MallGoods())->getBaseBylistPage([['islimit','=',0],['status','=',1]],$page,$limit,'id,title,logo,goods_price,market_price,stock','sort desc,id desc');
        }catch (\Exception $e){
            return Show::json_show(Status::mini_error,'查询失败');
        }
        return Show::json_show(Status::mini_normal,'ok',[
            'banner'=>$banner,
            'goods'=>$goods
        ]);
    }

    /**
     * 获取限时购商品列表
     * @return \think\response\Json
     */
    public function getLimitByGoods(){
        $keyword =$this->request->param('keyword','','trim');
        $page =$this->request->param('page',1,'intval');
        $order =$this->request->param('order','sort','trim');
        $limit =$this->request->param('limit',10,'intval');
        $latitude =$this->request->param('latitude','','trim');
        $longitude =$this->request->param('longitude','','trim');
        $lng =$longitude;
        $lat =$latitude;
        $where2 =[['g.islimit','=',1],['g.status','=',1]];
        $where33=[];
        if($keyword){
            $where2[]=[['g.title','like','%'.$keyword.'%']];
            $where33 =[['m.title','like','%'.$keyword.'%']];
        }
        try{
            if($order == 'gongli'){

               $goods= (new MallManagerDoor())->alias('d')->field('g.id,g.title,g.logo,g.goods_price,g.market_price,g.stock,d.lat,d.lng,ROUND(
                        6378.138 * 2 * ASIN(
                        SQRT(
                        POW(
                        SIN(
                        (
                        '.$lat.' * PI() / 180 - d.lat * PI() / 180
                        ) / 2
                        ),
                        2
                        ) + COS('.$lat.' * PI() / 180) * COS(d.lat * PI() / 180) * POW(
                        SIN(
                        (
                        '.$lng.' * PI() / 180 - d.lng * PI() / 180
                        ) / 2
                        ),
                        2
                        )
                        )
                        ) * 1000
                        ) AS
                        distance')
                   ->join('mall_door_goods dg','dg.door_id=d.id')
                   ->join('mall_goods g','g.id=dg.goods_id')
                   ->join('mall_manager m','m.id=g.manager_id')
                   ->where($where2)
                   ->whereOr($where33)
                   ->page($page,$limit)
                   ->order('distance asc')->group('g.id')->select()->toArray();
            }else{
                $goods= (new MallManagerDoor())->alias('d')
                    ->field('g.id,g.title,g.logo,g.goods_price,g.market_price,g.stock,d.lat,d.lng,
                        ROUND(
                        6378.138 * 2 * ASIN(
                        SQRT(
                        POW(
                        SIN(
                        (
                        '.$lat.' * PI() / 180 - d.lat * PI() / 180
                        ) / 2
                        ),
                        2
                        ) + COS('.$lat.' * PI() / 180) * COS(d.lat * PI() / 180) * POW(
                        SIN(
                        (
                        '.$lng.' * PI() / 180 - d.lng * PI() / 180
                        ) / 2
                        ),
                        2
                        )
                        )
                        ) * 1000
                        ) AS
                        distance')
                    ->join('mall_door_goods dg','dg.door_id=d.id')
                    ->join('mall_goods g','g.id=dg.goods_id')
                    ->join('mall_manager m','m.id=g.manager_id')
                    ->where($where2)
                    ->whereOr($where33)
                    ->page($page,$limit)
                   ->order('g.'.$order.' desc,id desc')
                    ->group('g.id')->select()->toArray();
            }

        }catch (\Exception $e){
            file_put_contents('a99012.txt',var_export($e->getMessage(),true).PHP_EOL,8);
            return Show::json_show(Status::mini_error,'查询失败');
        }

        foreach ($goods as $k=>$v){
            if($v['distance']>1000){
                $goods[$k]['distance'] =round($v['distance']/1000,2).'km';
            }else{
                $goods[$k]['distance'] =$v['distance'].'m';
            }
        }

        return Show::json_show(Status::mini_normal,'ok',[
            'goods'=>$goods
        ]);
    }

    public function  demo12(){
        $lat ='29.55491254';
        $lng='106.5485537';
//        $lat1='29.537324572919';
//        $lng1='106.51142151382';
        $lat1='29.726609';
        $lng1='106.59158';
        $res= Str::getShippingDistances($lng,$lat,$lng1,$lat1);
        return Show::json_show(Status::mini_normal,'ok',[
            'gongli'=>$res
        ]);
    }


    /**
     * 商品详情
     * @return \think\response\Json
     */
    public function goodsDetail(){
        $id =$this->request->param('id',0,'intval');
        $openid =$this->request->param('openid','','trim');
        try{
            $detail =(new MallGoods())->alias('g')->field('g.id,g.title,g.images,g.logo,g.short_title,g.tags,g.doors,g.market_price,g.sku_id,g.goods_price,g.sales,g.stock,m.title as shoptitle,m.m_image,g.buy_times,g.content,g.buydesc,g.status')->join('mall_manager m','m.id=g.manager_id')->where([['g.id','=',$id]])->find();
            $history =(new MallHistory())->getBaseByWhereOne([['goods_id','=',$id],['openid','=',$openid]]);
        }catch (\Exception $e){
            return Show::json_show(Status::mini_error,$e->getMessage());
        }
        if(!$detail){
            return Show::json_show(Status::mini_error,'商品不存在');
        }

        $detail['content'] =htmlspecialchars_decode($detail['content']);
        $detail['buydesc'] =htmlspecialchars_decode($detail['buydesc']);
        $tags =explode(',',$detail['tags']);
        $tagss=[];
        foreach ($tags as $k=>$v){
            $taginfo =(new MallTags())->getBaseById($v,'id,title');
            $tagss[$k]['title'] = !empty($taginfo) ?$taginfo['title']:'';
        }
        $detail['tags'] =$tagss;
        // 判断商品是否在可购时间段内
        $buytimes =explode(' - ',$detail['buy_times']);
        if(strtotime($buytimes[0])<=time() && time()<=strtotime($buytimes[1]) && $detail['stock']>0){
            $detail['tobuy']=1;
        }else{
            $detail['tobuy']=0;
        }
        $doors =explode(',',$detail['doors']);
        $detail['doorsnum'] =count($doors);
        $doorInfo =[];
        if($doors[0]>0){
            $doorInfo =(new MallManagerDoor())->alias('d')->field('d.id,d.title,m.logo,d.mobile,d.latlng,m_image')
                    ->join('mall_manager m','m.id=d.manager_id')
                    ->where([['d.id','=',$doors[0]]])->find()->toArray();
            $lats =explode(',',$doorInfo['latlng']);
            $doorInfo['lat'] =$lats[0];
            $doorInfo['lng'] =$lats[1];
        }
        $detail['doorInfo'] =$doorInfo;
        $detail['images'] =explode('|',$detail['images']);
        if(!$history){
            (new MallHistory())->save(['openid'=>$openid,'goods_id'=>$id]);
        }
        $collectinfo =(new MallCollect())->where([['product_id','=',$id],['openid','=',$openid]])->find();
        if($collectinfo){
            $detail['iscollect']=1;
        }else{
            $detail['iscollect']=0;
        }

        $detail['servicelogo'] =request()->domain().'/static/img/service.jpeg';
        $detail['zhekou']=round($detail['goods_price']/$detail['market_price']*10,1);
        return Show::json_show(Status::mini_normal,'ok',[
            'detail'=>$detail,

        ]);
    }
    /**
     * 商品详情
     * @return \think\response\Json
     */
    public function goodsDetailV2(){
        $id =$this->request->param('id',0,'intval');
        $openid =$this->request->param('openid','','trim');
        try{
            $detail =(new MallGoods())->alias('g')->field('g.id,g.title,g.images,g.logo,g.short_title,g.tags,g.doors,g.market_price,g.sku_id,g.goods_price,g.sales,g.stock,m.title as shoptitle,m.m_image,g.buy_times,g.content,g.buydesc,g.status')->join('mall_manager m','m.id=g.manager_id')->where([['g.id','=',$id]])->find();
            $history =(new MallHistory())->getBaseByWhereOne([['goods_id','=',$id],['openid','=',$openid]]);
        }catch (\Exception $e){
            return Show::json_show(Status::mini_error,$e->getMessage());
        }
        if(!$detail){
            return Show::json_show(Status::mini_error,'商品不存在');
        }

        $detail['content'] =htmlspecialchars_decode($detail['content']);
        $detail['buydesc'] =htmlspecialchars_decode($detail['buydesc']);
        $tags =explode(',',$detail['tags']);
        $tagss=[];
        foreach ($tags as $k=>$v){
            $taginfo =(new MallTags())->getBaseById($v,'id,title');
            $tagss[$k]['title'] = !empty($taginfo) ?$taginfo['title']:'';
        }
        $detail['tags'] =$tagss;
        // 判断商品是否在可购时间段内
        $buytimes =explode(' - ',$detail['buy_times']);
        if(strtotime($buytimes[0])<=time() && time()<=strtotime($buytimes[1]) && $detail['stock']>0){
            $detail['tobuy']=1;
        }else{
            $detail['tobuy']=0;
        }
        $doors =explode(',',$detail['doors']);
        $detail['doorsnum'] =count($doors);
        $doorInfo =[];
        if($doors[0]>0){
            $doorInfo =(new MallManagerDoor())->alias('d')->field('d.id,d.title,m.logo,d.mobile,d.latlng,m_image')
                ->join('mall_manager m','m.id=d.manager_id')
                ->where([['d.id','=',$doors[0]]])->find()->toArray();
            $lats =explode(',',$doorInfo['latlng']);
            $doorInfo['lat'] =$lats[0];
            $doorInfo['lng'] =$lats[1];
        }
        $detail['doorInfo'] =$doorInfo;
        $detail['images'] =explode('|',$detail['images']);
        if(!$history){
            (new MallHistory())->save(['openid'=>$openid,'goods_id'=>$id]);
        }
        $collectinfo =(new MallCollect())->where([['product_id','=',$id],['openid','=',$openid]])->find();
        if($collectinfo){
            $detail['iscollect']=1;
        }else{
            $detail['iscollect']=0;
        }

        //查询sku信息
        try {
            $sku = (new MallGoodsSku())->getBaseByWhere([['goods_id','=',$id]]);
        } catch (\Exception $e) {
            Log::error("goods_Sku" . $e->getMessage() . " " . $e->getFile() . "　" . $e->getLine());
            return Show::json_show(Status::mini_error, "查询错误");
        }
        if (!empty($sku)) {
            $skus = [];
            foreach ($sku as $value) {
                if (empty($value['specs_value_ids'])) {
                    //单商品
                    $skus[] = [];
                } else {
                    //多商品
                    $key = explode('-', $value['specs_value_ids']);
                    foreach ($key as $v) {
                        $skus[] = $v;
                    }
                }
            }
            if (!empty($skus[0])) {
                $specs = array_unique($skus);

                try {
                    $specs_value_data = (new MallSpecsValue())->field('id,title as name,specs_id,specs_id as pid')
                        ->where('id', 'in', $specs)
                        ->select()
                        ->toArray();
                } catch (\Exception $e) {
                    return Show::json_show(Status::mini_error, "sku信息错误");
                }
                $specs_ids = array_column($specs_value_data, "specs_id");
                try {
                    $specs_data = (new MallSpecs())->field("id,title as name")
                        ->where('id', 'in', $specs_ids)
                        ->select()
                        ->toArray();
                } catch (\Exception $e) {
                    return Show::json_show(Status::mini_error, "sku信息错误");
                }

                $detail['skus'] = [
                    "specs_data" => $specs_data ?? [],
                    "specs_value_data" => $specs_value_data
                ];
            } else {
                $detail['skus'] = [];
            }
        } else {
            return Show::json_show(Status::mini_error, "商品sku不存在");
        }

        $detail['servicelogo'] =request()->domain().'/static/img/service.jpeg';
        $detail['zhekou']=round($detail['goods_price']/$detail['market_price']*10,1);
        return Show::json_show(Status::mini_normal,'ok',[
            'detail'=>$detail,

        ]);
    }

    /**
     * @return \think\response\Json
     */
    public function getGoodsSpecsByList()
    {
        $goods_id = $this->request->param('goods_id', 0, 'intval');
        $specs = $this->request->param('specs');

        $specs_value = "";
        if (empty($specs)) {
            return Show::json_show(Status::mini_error, "规格不存在");
        }
        $specs_id = array_column($specs, "id");
        $specs_value = implode('-', $specs_id);
        try {
            $skus = (new MallGoodsSku())->field('id,image as logo,stock,price as goods_price')
                ->where('goods_id', $goods_id)
                ->where('specs_value_ids', "like", "%$specs_value%")
                ->find();
        } catch (\Exception $e) {
            return Show::json_show(Status::mini_error, "查询失败");
        }
        if (!$skus) {
            return Show::json_show(Status::mini_normal, "ok");
        }
        $result = $skus->toArray();
        return Show::json_show(Status::mini_normal, 'ok', $result);
    }


    /**
     * 检查商品信息
     * @return \think\response\Json
     */
    public function checkGoods(){
        $goods_id = $this->request->param('id', 0, 'intval');
        try {
            $goods = (new MallGoods())->getBaseById($goods_id, 'id,cate_id,title,status');
        } catch (\Exception $e) {

            return Show::json_show(Status::mini_error, "查询错误");
        }
        if (!$goods) {
            return Show::json_show(Status::mini_error, "商品不存在");
        }
        return Show::json_show(Status::mini_normal, "ok", [
            'goods'=>$goods
        ]);
    }


    /**
     * 领券中心
     * @return \think\response\Json
     */
    public function getBonus(){
        $page =$this->request->param('page',1,'intval');
        $openid =$this->request->param('openid','','trim');
        $limit =$this->request->param('limit',10,'intval');
        try{
            $list =(new MallBonus())->getBaseBylistPage([['status','=',1]],$page,$limit,'id,title,money,FROM_UNIXTIME(starttime,"%Y-%m-%d") as starttime,FROM_UNIXTIME(endtime,"%Y-%m-%d") as endtime');
        }catch (\Exception $e){
            return Show::json_show(Status::mini_error,'查询失败');
        }
        foreach ($list as $k=>$v){
            $bonusinfo =(new MallUserBonus())->where([['openid','=',$openid],['bonus_id','=',$v['id']]])->find();
            if($bonusinfo){
                $list[$k]['isget'] =1;
            }else{
                $list[$k]['isget'] =0;
            }
        }
        return Show::json_show(Status::mini_normal,'ok',[
           'list'=>$list
        ]);
    }

    /**
     * 门店二维码生成
     * @return \think\response\Json
     * @throws \think\Exception
     */
    public function doorCode(){
        $door_id =$this->request->param('door_id',0,'intval');
        $openid =$this->request->param('openid','','trim');

        try{
            $accessToken =(new MallAccessToken())->find(1);
        }catch (\Exception $e){
            return Show::json_show(Status::mini_error,'查询失败');
        }
        if(!$accessToken){
            return Show::json_show(Status::mini_error,'系统内部错误');
        }
        if($accessToken['expire_time']<=time()){
           $response= Toutiao::getInstance()->getAccessToken();
           if($response['err_no'] ==0){
               $token =$response['data']['access_token'];
               $accessToken->save(['token'=>$token,'expire_time'=>time()+$response['data']['expires_in']]);
           }else{
               return Show::json_show(Status::mini_error,'系统内部错误');
           }
        }else{
            $token =$accessToken['token'];
        }

        try{
              $query ='id_'.$door_id;
              $path= urlencode("pages/my/my?spcode=".$query);
              $result= Toutiao::getInstance()->createQRCode($token,'douyin',$path,$door_id,$query);
        }catch (\Exception $e){
            return Show::json_show(Status::mini_error,$e->getMessage());
        }

        return Show::json_show(Status::mini_normal,'ok',[
           'code'=>$result
        ]);
    }

    /**
     * 商品所属门店
     * @return \think\response\Json
     */
    public function  managerDoor(){
        $id =$this->request->param('id','','intval');
        try{
            $goods =(new MallGoods())->getBaseById($id);
            $doors= (new MallDoorGoods())->alias('dg')
                ->field('d.*')
                ->join('mall_manager_door d','d.id=dg.door_id')
                ->where([['dg.goods_id','=',$id]])
                ->select()->toArray();
        }catch (\Exception $e){
            return Show::json_show(Status::mini_error,$e->getMessage());
        }
        if(!$goods || !$goods['doors']){
            return Show::json_show(Status::mini_error,'参数有误');
        }

        return Show::json_show(Status::mini_normal,'ok',[
            'doors'=>$doors
        ]);

    }


}